package main.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * AOP处理请求日志
 * @author wfy
 *
 */
@Aspect
@Component
public class HttpAspect {

	private final static Logger LOG = LoggerFactory.getLogger(HttpAspect.class);
	
	@Pointcut("execution(public * main.controller.*.*(..))")
	
	public void log() {
	}
	
	@Before("log()")
	public void doBefore(JoinPoint joinPoint) {
		LOG.info("处理http请求");
		ServletRequestAttributes servletRequsetAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = servletRequsetAttributes.getRequest();
		
		//url
		LOG.info("url={}",request.getRequestURL());
		
		//method
		LOG.info("method={}",request.getMethod());
		
		//ip
		LOG.info("ip={}",request.getRemoteAddr());
		
		//类方法
		LOG.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+ "." + joinPoint.getSignature().getName());
		
		//参数
		LOG.info("args={}",joinPoint.getArgs());
		
	}
	
	@After("log()")
	public void doAfter() {
		LOG.info("处理请求结束啦");
	}
	
	@AfterReturning(returning="object",pointcut = "log()")
	public void doAfterReturning(Object object) {
		LOG.info("response={}",object.toString());
	}
}
